<template>
  <div class="home-dashboard">
    <div class="stats-cards">
      <div class="card">
        <h3>医师数量</h3>
        <p class="stat-number">{{ stats.doctors }}</p>
      </div>
      <div class="card">
        <h3>药品数量</h3>
        <p class="stat-number">{{ stats.medicines }}</p>
      </div>
      <div class="card">
        <h3>合作公司数量</h3>
        <p class="stat-number">{{ stats.companies }}</p>
      </div>
      <div class="card">
        <h3>药店数量</h3>
        <p class="stat-number">{{ stats.locations }}</p>
      </div>
    </div>

    <!-- 医生类别和等级数量展示 -->
    <div class="doctor-count-section">
      <div class="doctor-level-count">
        <h4>医生等级数量分布</h4>
        <div id="doctor-level-bar" style="width: 100%; max-width: 630px; height: 450px; margin: 0 auto;"></div>
      </div>
      <div class="doctor-category-count">
        <h4>医生类别数量分布</h4>
        <div id="doctor-category-pie" style="width: 100%; max-width: 630px; height: 450px; margin: 0 auto;"></div>
      </div>
    </div>

    <div class="policy-announcement-section">
      <div class="policy-list-block">
        <div class="policy-list-header">
          <span class="policy-list-title">医药公司政策</span>
          <a class="policy-list-more" href="#" @click="goToAllPolicies">查看更多→</a>
        </div>
        <ul class="policy-list">
          <li v-for="(item, idx) in companyPolicies.slice(0, 7)" :key="item.id" class="policy-list-item">
            <span class="policy-date">{{ formatDate(item.updateTime) }}</span>
            <span class="policy-title policy-link" :title="item.name" @click.stop="openDetail(item, 'company')">{{ item.name }}</span>
            <span v-if="idx < 3" class="policy-new">New</span>
          </li>
        </ul>
      </div>
      <div class="policy-list-block">
        <div class="policy-list-header">
          <span class="policy-list-title">医保政策</span>
          <a class="policy-list-more" href="#" @click="goToAllPolicies">查看更多→</a>
        </div>
        <ul class="policy-list">
          <li v-for="(item, idx) in medicalPolicies.slice(0, 7)" :key="item.id" class="policy-list-item">
            <span class="policy-date">{{ formatDate(item.updateTime) }}</span>
            <span class="policy-title policy-link" :title="item.name" @click.stop="openDetail(item, 'medical')">{{ item.name }}</span>
            <span v-if="idx < 3" class="policy-new">New</span>
          </li>
        </ul>
      </div>
    </div>
    <div v-if="showDetailModal" class="modal-overlay" @click="closeDetail">
      <div class="modal-content detail-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ detailType === 'company' ? '医药公司政策详情' : '医保政策详情' }}</h3>
          <button class="close-btn" @click="closeDetail">&times;</button>
        </div>
        <div class="modal-body">
          <div class="detail-item">
            <label>政策标题：</label>
            <div class="detail-content">{{ detailData.name }}</div>
          </div>
          <div class="detail-item">
            <label>政策内容：</label>
            <div class="detail-content">{{ detailData.policy }}</div>
          </div>
          <div class="detail-item">
            <label>添加时间：</label>
            <div class="detail-content">{{ formatDate(detailData.updateTime) }}</div>
          </div>
        </div>
        <div class="modal-footer">
          <button class="cancel-btn" @click="closeDetail">关闭</button>
        </div>
      </div>
    </div>
    <div class="add-bottom-space">&nbsp;</div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, watch } from 'vue'
import axios from 'axios'
import * as echarts from 'echarts'

const stats = ref({
  doctors: 0,
  medicines: 0,
  companies: 0,
  locations: 0
})

const doctorCategoryData = ref({})
const doctorLevelData = ref({})
const allLevels = ["实习医师","住院医师","主治医师","副主任医师","主任医师"]

const companyPolicies = ref([])
const medicalPolicies = ref([])
const showDetailModal = ref(false)
const detailType = ref('company')
const detailData = ref({})

function formatDate(dateStr) {
  if (!dateStr) return ''
  const d = new Date(dateStr)
  return `${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
}

async function fetchStats() {
  try {
    // 医师数量
    const doctorRes = await axios.get('http://47.93.134.56:8800/doctor/get/count');
    if (doctorRes.data.code === 200) stats.value.doctors = doctorRes.data.data;
    // 药品数量
    const medicineRes = await axios.get('http://47.93.134.56:8800/medical/get/count');
    if (medicineRes.data.code === 200) stats.value.medicines = medicineRes.data.data;
    // 公司数量
    const companyRes = await axios.get('http://47.93.134.56:8800/company/get/count');
    if (companyRes.data.code === 200) stats.value.companies = companyRes.data.data;
    // 药店数量
    const locationRes = await axios.get('http://47.93.134.56:8800/pharmacy/get/count');
    if (locationRes.data.code === 200) stats.value.locations = locationRes.data.data;
  } catch (e) {
    // 可选：处理错误
  }
}

async function fetchDoctorCategoryCount() {
  try {
    const res = await axios.get('http://47.93.134.56:8800/doctor/get/category/count')
    if (res.data.code === 200) doctorCategoryData.value = res.data.data || {}
  } catch (e) {}
}

async function fetchDoctorLevelCount() {
  try {
    const res = await axios.get('http://47.93.134.56:8800/doctor/get/level/count')
    if (res.data.code === 200) doctorLevelData.value = res.data.data || {}
  } catch (e) {}
}

async function fetchCompanyPolicies() {
  try {
    const res = await axios.get('http://47.93.134.56:8800/company_policy/getall')
    if (res.data.code === 200) {
      companyPolicies.value = res.data.data
    }
  } catch (e) {}
}

async function fetchMedicalPolicies() {
  try {
    const res = await axios.get('http://47.93.134.56:8800/medical_policy/getall')
    if (res.data.code === 200) {
      medicalPolicies.value = res.data.data
    }
  } catch (e) {}
}

function openDetail(item, type) {
  detailType.value = type
  detailData.value = item
  showDetailModal.value = true
}

function closeDetail() {
  showDetailModal.value = false
}

function goToAllPolicies(e) {
  e.preventDefault();
  window.location.href = window.location.origin + window.location.pathname + '#policy';
  window.dispatchEvent(new CustomEvent('switchToPolicy'));
}

function renderDoctorLevelBar() {
  const dom = document.getElementById('doctor-level-bar')
  if (!dom) return
  if (echarts.getInstanceByDom(dom)) echarts.dispose(dom)
  const chart = echarts.init(dom)
  const data = allLevels.map(l => doctorLevelData.value[l] || 0)
  chart.setOption({
    tooltip: {},
    xAxis: { type: 'category', data: allLevels },
    yAxis: { type: 'value' },
    series: [{
      name: '数量',
      type: 'bar',
      data,
      label: { show: true, position: 'top' }
    }]
  })
}

function renderDoctorCategoryPie() {
  const dom = document.getElementById('doctor-category-pie')
  if (!dom) return
  if (echarts.getInstanceByDom(dom)) echarts.dispose(dom)
  const chart = echarts.init(dom)
  const data = Object.entries(doctorCategoryData.value).map(([name, value]) => ({ name, value }))
  chart.setOption({
    tooltip: { trigger: 'item' },
    legend: { top: 'bottom' },
    series: [{
      name: '医生类别',
      type: 'pie',
      radius: '60%',
      data,
      label: { formatter: '{b}: {c} ({d}%)' }
    }]
  })
}

onMounted(() => {
  fetchStats();
  fetchDoctorCategoryCount();
  fetchDoctorLevelCount();
  fetchCompanyPolicies();
  fetchMedicalPolicies();
  nextTick(() => {
    renderDoctorLevelBar();
    renderDoctorCategoryPie();
  });
});

watch(doctorLevelData, () => {
  nextTick(() => {
    renderDoctorLevelBar();
  });
});

watch(doctorCategoryData, () => {
  nextTick(() => {
    renderDoctorCategoryPie();
  });
});
</script>

<style scoped>
.home-dashboard {
  width: 100%;
  height: 100%;
  display: flex;
  flex-direction: column;
  justify-content: flex-start;
  align-items: stretch;
  padding: 0;
  margin: 0;
  min-height: 100%;
}

.stats-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 30px;
  margin-bottom: 40px;
  width: 100%;
}

.card {
  background-color: white;
  padding: 25px;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08);
  transition: all 0.3s ease;
  height: 100%;
  min-height: 120px;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.card:hover {
  transform: translateY(-5px);
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.12);
}

.card h3 {
  margin: 0 0 10px 0;
  font-size: 1rem;
  color: #555;
  font-weight: 500;
}

.stat-number {
  margin: 0;
  font-size: 2.5rem;
  font-weight: 600;
  color: #2c3e50;
}

.welcome-message {
  font-size: 1.1rem;
  color: #666;
  margin: 0;
  padding: 20px 0;
}

.policy-announcement-section {
  display: flex;
  gap: 40px;
  margin-bottom: 40px;
  margin-top: 10px;
}
.policy-list-block {
  flex: 1;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  padding: 20px 25px 10px 25px;
  min-width: 0;
  display: flex;
  flex-direction: column;
}
.policy-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 2px solid #1abc9c;
  padding-bottom: 8px;
  margin-bottom: 10px;
}
.policy-list-title {
  font-size: 1.2rem;
  font-weight: 600;
  color: #222;
  display: flex;
  align-items: center;
}
.policy-list-more {
  color: #1abc9c;
  font-size: 1rem;
  text-decoration: none;
  transition: color 0.2s;
}
.policy-list-more:hover {
  color: #16a085;
  text-decoration: underline;
}
.policy-list {
  list-style: none;
  margin: 0;
  padding: 0;
}
.policy-list-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px dashed #e0e0e0;
  font-size: 1rem;
  color: #333;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.policy-date {
  color: #1abc9c;
  font-weight: 600;
  margin-right: 16px;
  min-width: 48px;
  font-size: 1.1rem;
  font-family: 'Consolas', monospace;
}
.policy-title {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.policy-new {
  background: #e74c3c;
  color: #fff;
  font-size: 0.85rem;
  border-radius: 8px;
  padding: 2px 10px;
  margin-left: 10px;
  font-weight: 600;
}
.policy-link {
  color: #222;
  cursor: pointer;
  text-decoration: none;
  transition: color 0.2s;
}
.policy-link:hover {
  color: #222;
  text-decoration: none;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .stats-cards {
    grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
    gap: 20px;
  }
  
  .card {
    padding: 20px;
    min-height: 100px;
  }
  
  .stat-number {
    font-size: 2rem;
  }
}

@media (max-width: 768px) {
  .stats-cards {
    grid-template-columns: repeat(2, 1fr);
    gap: 15px;
  }
  
  .card {
    padding: 15px;
    min-height: 80px;
  }
  
  .stat-number {
    font-size: 1.8rem;
  }
  
  .welcome-message {
    font-size: 1rem;
    padding: 15px 0;
  }
}

@media (max-width: 480px) {
  .stats-cards {
    grid-template-columns: 1fr;
    gap: 15px;
  }
  
  .card {
    padding: 15px;
    min-height: 70px;
  }
  
  .stat-number {
    font-size: 1.5rem;
  }
}

/* 复用政策管理的弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 1000;
}
.modal-content.detail-modal {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 20px 60px rgba(0,0,0,0.3);
  width: 90%;
  max-width: 500px;
  max-height: 80vh;
  overflow-y: auto;
  animation: slideIn 0.3s ease;
  border: 1px solid #e0e0e0;
}
@keyframes slideIn {
  from { opacity: 0; transform: translateY(-50px) scale(0.95); }
  to { opacity: 1; transform: translateY(0) scale(1); }
}
.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 25px 25px 20px 25px;
  border-bottom: 2px solid #3498db;
}
.modal-header h3 {
  margin: 0;
  color: #2c3e50;
  font-size: 1.4rem;
  font-weight: 600;
}
.close-btn {
  background: none;
  border: none;
  font-size: 1.5rem;
  color: #999;
  cursor: pointer;
  padding: 0;
  width: 35px;
  height: 35px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 50%;
  transition: all 0.3s ease;
}
.close-btn:hover {
  background: #f0f0f0;
  color: #333;
  transform: scale(1.1);
}
.modal-body {
  padding: 25px;
}
.detail-item {
  margin-bottom: 20px;
}
.detail-item label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 600;
  font-size: 0.95rem;
}
.detail-content {
  padding: 12px;
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  color: #333;
  line-height: 1.6;
  min-height: 20px;
  word-wrap: break-word;
}
.modal-footer {
  display: flex;
  justify-content: center;
  gap: 15px;
  padding: 20px 25px 25px 25px;
  border-top: 1px solid #e0e0e0;
}
.cancel-btn {
  background: linear-gradient(135deg, #95a5a6, #7f8c8d);
  color: white;
  box-shadow: 0 4px 15px rgba(149, 165, 166, 0.3);
  padding: 12px 30px;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 100px;
}
.cancel-btn:hover {
  background: linear-gradient(135deg, #7f8c8d, #6c7b7d);
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(149, 165, 166, 0.4);
}

/* 医生类别和等级数量展示 */
.doctor-count-section {
  display: flex;
  flex-direction: column;
  gap: 32px;
  margin-bottom: 40px;
  margin-top: 10px;
}
.doctor-level-count, .doctor-category-count {
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 4px 12px rgba(0,0,0,0.08);
  padding: 20px 25px 10px 25px;
  min-width: 0;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.doctor-level-count h4, .doctor-category-count h4 {
  margin: 0 0 10px 0;
  font-size: 1rem;
  color: #555;
  font-weight: 500;
}

.add-bottom-space {
  height: 40px;
  width: 100%;
}
</style> 